"""
Checkout process utilities.
"""

from django.contrib.auth.models import SiteProfileNotAvailable
from django.utils.translation import ugettext as _
from django.template.loader import get_template, TemplateDoesNotExist

from mezzanine.conf import settings
from mezzanine.utils.email import send_mail_template

from cartridge.shop.models import Order
from cartridge.shop.utils import set_shipping, sign

from db_conn_soundcloud import *
from datetime import datetime, timedelta
from time import localtime, strptime, strftime

def add_soundcloud_play(url,login_request,to_play):
    cursor,conn = db_connect()
    data_entrada = (datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
    add_soundcloud_play_query = """
    INSERT INTO `plays` (`url`, `login_request`, `to_play`, `data_entrada`) VALUES ('%s', '%s', %s, '%s');
    """ % (url,login_request,to_play,data_entrada)
    cursor.execute(add_soundcloud_play_query)
    db_disconnect(cursor,conn)

def default_billship_handler(request, order_form):
    """
    Default billing/shipping handler - called when the first step in
    the checkout process with billing/shipping address fields is
    submitted. Implement your own and specify the path to import it
    from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``.
    This function will typically contain any shipping calculation
    where the shipping amount can then be set using the function
    ``cartridge.shop.utils.set_shipping``. The Cart object is also
    accessible via ``request.cart``
    """
    if not request.session.get('free_shipping'):
        settings.use_editable()
        set_shipping(request, _("Flat rate shipping"),
                     settings.SHOP_DEFAULT_SHIPPING_VALUE)


def default_payment_handler(request, order_form, order):
    """
    Default payment handler - called when the final step of the
    checkout process with payment information is submitted. Implement
    your own and specify the path to import it from via the setting
    ``SHOP_HANDLER_PAYMENT``. This function will typically contain
    integration with a payment gateway. Raise
    cartridge.shop.checkout.CheckoutError("error message") if payment
    is unsuccessful.
    """
    pass


def default_order_handler(request, order_form, order):
    """
    Default order handler - called when the order is complete and
    contains its final data. Implement your own and specify the path
    to import it from via the setting ``SHOP_HANDLER_ORDER``.
    """
    post_data = dict(request.POST.items())
    
    add_soundcloud_play(post_data["url_soundcloud"],request.user.email,1000)
    #request.session["url_soundcloud"]
    #order_context = {"order": order, "request": request,
    #                 "order_items": order.items.all()}
    #order_context.update(order.details_as_dict())
    #print order_context



def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.use_editable()
    order_context = {"order": order, "request": request,
                     "order_items": order.items.all()}
    order_context.update(order.details_as_dict())
    try:
        get_template("shop/email/order_receipt.html")
    except TemplateDoesNotExist:
        receipt_template = "email/order_receipt"
    else:
        receipt_template = "shop/email/order_receipt"
        from warnings import warn
        warn("Shop email receipt templates have moved from "
             "templates/shop/email/ to templates/email/")
    send_mail_template(settings.SHOP_ORDER_EMAIL_SUBJECT,
        receipt_template, settings.SHOP_ORDER_FROM_EMAIL,
        order.billing_detail_email, context=order_context,
        fail_silently=settings.DEBUG)

